package com.demandbreakdown.xiyun.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.demandbreakdown.xiyun.common.base.ResultCode;
import com.demandbreakdown.xiyun.common.exception.BusinessException;
import com.demandbreakdown.xiyun.service.EmailService;
import com.demandbreakdown.xiyun.service.SecurityControlService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

import static com.demandbreakdown.xiyun.common.constant.SecurityConstant.*;

/**
 * 邮件服务实现类
 *
 * @author poxz
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class EmailServiceImpl implements EmailService {

    // Service 层依赖
    private final SecurityControlService securityControlService;

    // 工具类依赖
    private final RedisTemplate<String, Object> redisTemplate;
    private final JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromEmail;

    @Override
    public void sendCaptcha(String email) {
        // 检查IP频率限制
        String clientIp = securityControlService.getClientRealIp();
        if (!securityControlService.checkIpRateLimit(clientIp, OPERATION_SEND_CAPTCHA)) {
            throw new BusinessException(ResultCode.EMAIL_SEND_TOO_FREQUENT);
        }

        // 检查邮箱验证码发送频率限制
        if (securityControlService.checkEmailCaptchaLimit(email)) {
            throw new BusinessException(ResultCode.EMAIL_SEND_TOO_FREQUENT);
        }

        // 生成验证码
        String captcha = RandomUtil.randomNumbers(CAPTCHA_LENGTH);

        // 存储验证码到Redis
        String captchaKey = CAPTCHA_KEY_PREFIX + email;
        redisTemplate.opsForValue().set(captchaKey, captcha, CAPTCHA_EXPIRE_MINUTES, TimeUnit.MINUTES);

        // 发送邮件
        try {
            sendVerificationEmail(email, captcha);

            // 开发测试：直接在日志中打印验证码
            log.warn("=".repeat(60));
            log.warn("📧 验证码已生成");
            log.warn("邮箱: {}", email);
            log.warn("验证码: {}", captcha);
            log.warn("有效期: {} 分钟", CAPTCHA_EXPIRE_MINUTES);
            log.warn("=".repeat(60));

            // 记录发送行为
            securityControlService.recordEmailCaptchaSent(email);
        } catch (Exception e) {
            log.error("验证码处理失败: 邮箱={}, 错误={}", email, e.getMessage());
            throw new BusinessException(ResultCode.SYSTEM_ERROR);
        }
    }

    @Override
    public boolean verifyCaptcha(String email, String captcha) {
        String captchaKey = CAPTCHA_KEY_PREFIX + email;
        String storedCaptcha = (String) redisTemplate.opsForValue().get(captchaKey);

        if (storedCaptcha == null) {
            return false;
        }

        boolean isValid = storedCaptcha.equals(captcha);
        if (isValid) {
            // 验证成功后删除验证码
            redisTemplate.delete(captchaKey);
        }

        return isValid;
    }

    @Override
    public void sendSimpleEmail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        try {
            mailSender.send(message);
        } catch (Exception e) {
            log.error("邮件发送失败: 收件人={}, 主题={}, 错误={}", to, subject, e.getMessage());
            throw new BusinessException(ResultCode.SYSTEM_ERROR);
        }
    }

    /**
     * 发送验证码邮件
     */
    private void sendVerificationEmail(String toEmail, String captcha) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(fromEmail);
        message.setTo(toEmail);
        message.setSubject("【栖云图库】您的验证码：" + captcha);

        String content = buildVerificationEmailContent(captcha);
        message.setText(content);
        mailSender.send(message);
    }

    /**
     * 构建验证码邮件内容
     */
    private String buildVerificationEmailContent(String captcha) {
        return String.format(
                "═══════════════════════════════════════\n" +
                        "           栖 云 图 库\n" +
                        "       XIYUN GALLERY SYSTEM\n" +
                        "═══════════════════════════════════════\n\n" +
                        "尊敬的用户，您好！\n\n" +
                        "您正在进行邮箱验证操作，本次请求的验证码为：\n\n" +
                        "┌─────────────────────────────────────┐\n" +
                        "│                                     │\n" +
                        "│          验证码：%s          │\n" +
                        "│                                     │\n" +
                        "│        有效期：%d 分钟              │\n" +
                        "│                                     │\n" +
                        "└─────────────────────────────────────┘\n\n" +
                        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n" +
                        "【安全提示】\n" +
                        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" +
                        "• 验证码用于身份验证，请勿泄露给他人\n" +
                        "• 如非本人操作，请立即忽略此邮件\n" +
                        "• 验证码仅可使用一次，使用后自动失效\n" +
                        "• 系统不会通过电话或短信索要验证码\n\n" +
                        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n" +
                        "此邮件由系统自动发送，请勿直接回复。\n" +
                        "如有疑问，请访问帮助中心或联系客服。\n\n" +
                        "祝您使用愉快！\n\n" +
                        "栖云图库团队 敬上\n" +
                        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n" +
                        "© 2025 XIYUN Gallery. All rights reserved.\n" +
                        "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━",
                captcha, CAPTCHA_EXPIRE_MINUTES
        );
    }
}
